<template>
  <yt-page title="现场检查方案">
    <yt-form>
      <yt-cell label="文书编号" :value="form.document_num" />
      <yt-cell label="被检查企业" :value="form.enterprise_id ? form.enterprise_id.attributes.EnterpriseName : ''" />
      <yt-cell label="检查时间">
        <yt-cell-time v-model="form.check_time" />
      </yt-cell>
      <yt-cell label="检查人员">
        <yt-cell-select v-model="form.check_person" :max="5" :list="userList" label="DisplayName" val="id" />
      </yt-cell>
      <yt-cell label="检查方式">
        <yt-cell-select v-model="form.check_mode" :max="3" :list="modeList" label="D_text" val="D_code" />
      </yt-cell>
      <yt-cell label="检查内容" value="添加" border="none" isLink @click="goContent" />
      <yt-textarea class="input" type="column" v-model="form.check_content" ref="input"></yt-textarea>
      <yt-btn v-if="form.state === 0" slot="btn" :loading="onSubmit" theme="blue" edge>保存</yt-btn>
      <yt-btn-group v-else slot="btn" :shadow="false" edge>
        <yt-btn theme="white" :loading="onSubmit" :loadingOption="{color: '#46baff'}">保存</yt-btn>
        <yt-btn theme="white" :loading="onPreview" :loadingOption="{color: '#46baff'}">预览文书</yt-btn>
      </yt-btn-group>
    </yt-form>
  </yt-page>
</template>

<script>
import { EVENTS, BUS } from '@/store'
import { PointerToString, BuildPointer } from '@/common/utils/index.js'
import { commonApi } from '@/common/api/commonApi.js'
import { bridge } from '@/common/plugin/index.js'

export default {
  data() {
    return {
      form: {
        check_time: ''
      },
      userList: [],
      modeList: []
    }
  },
  activated() {
    if (!this.$router.$isBack) {
      this.init()
      this.fetchData()
    }
  },
  created() {
    BUS.$on(EVENTS.lawProgrammeContent, list => {
      let check_content = list
        .map((v, index) => `${index + 1} : ${v}。\n`)
        .join('')
      this.form = { ...this.form, check_content }
      setTimeout(() => {
        this.$refs.input.updateAutosize()
      }, 30)
    })
  },
  methods: {
    async onPreview(loaded) {
      try {
        let word = await commonApi.runCloud('officeCopy', {
          code: 'D0001',
          data: this.$route.query.id
        })
        let { url } = await commonApi.runCloud('WordToPdf', { word })
        if (!url) {
          this.$Toast('文件转换失败，请尝试重新预览！', 'error')
          loaded()
          return
        }
        bridge.PreviewPdf({ title: '文件标题', url: url })
      } catch (e) {}
      loaded()
    },
    goContent() {
      this.$router.$push('/law/programmeContent')
    },
    async init() {
      this.programme = this.$route.query.programme
      let form = await commonApi.searchById('law_programme', this.programme, {
        include: ['enterprise_id']
      })
      this.form = PointerToString(form, ['check_person:array'])
      if (this.form.document_num) return
      let { D0001 } = await commonApi.runCloud('lawGetDocumentNum', {
        year: new Date().getFullYear()
      })
      this.form = { ...this.form, document_num: D0001 }
    },
    async fetchData() {
      let p = [
        commonApi.search('aj_organization_personnel', {
          include: ['OrganizationIds'],
          matchesQuery: {
            OrganizationIds: commonApi.createQueryIncludeOptions(
              'sys_organizations',
              {
                equalTo: {
                  Name: '安监局执法'
                }
              }
            )
          }
        }),
        commonApi.dictionary('check_mode')
      ]
      let [userList, modeList] = await Promise.all(p)
      this.userList = userList
      this.modeList = modeList
    },
    async onSubmit(loaded) {
      try {
        let form = BuildPointer(this.form, {
          check_person: 'aj_organization_personnel'
        })
        if (form.state !== 1) {
          form.state = 1
          form.auditState = 0
        }
        await commonApi.save('law_programme', form)
        this.$router.$back()
        this.$Toast('新增成功!', 'success')
      } catch (e) {
        this.$Toast('新增失败!', 'error')
      }
      loaded()
    }
  }
}
</script>

<style scoped lang="stylus">
.input
  >>> .yt-textarea-input
    min-height 120px
</style>
